<?php

class User extends Eloquent
{
    public function group()
    {
        return $this->belongs_to('Group');
    }

    public function prichannels()
    {
        return $this->has_many('Prichannel');
    }

    public function isSelectedChannel()
    {
        return $this->prichannels()->count() > 0;
    }

    public static function results($userId, $start = null, $end = null)
    {
        $query = static::find($userId)->prichannels()
            ->join('results', function ($join) {
                $join->on('prichannels.channel_id', '=', 'results.channel_id')
                    ->on('prichannels.weekday', '=', 'results.weekday');
            });
        if (!is_null($start))
        {
            $query = $query->where('results.date', '<', $start);
        }

        if (!is_null($end))
        {
            $query = $query->where('results.date', '>=', $end);
        }

        return $query->order_by('date', 'desc')
            ->get();
    }
}